package com.network.proxy;

import com.network.proxy.adapter.CallAdapter;
import com.network.proxy.adapter.SimpleCallAdapter;
import com.network.proxy.converter.Converter;
import com.network.proxy.converter.ConverterFactory;
import com.network.proxy.converter.GsonConverterFactory;

import java.lang.reflect.Proxy;
import java.lang.reflect.Type;

/**
 * Created by kkmike999 on 2016/06/04.
 */
public class MyRetrofit {

	CallAdapter      adapter;
	ConverterFactory converterFactory;

	public MyRetrofit(CallAdapter adapter, ConverterFactory converterFactory) {
		this.adapter = adapter;
		this.converterFactory = converterFactory;
	}

	public <T> T create(Class<T> clazz) {
		if (!clazz.isInterface()) {
			throw new RuntimeException("Service not interface");
		}

		return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new ServiceProxy(this));
	}

	public Converter converter(Type returnType) {
		return converterFactory.getConverter(returnType);
	}

	public CallAdapter callAdapter() {
		return adapter;
	}

	public static class Builder {
		CallAdapter      adapter;
		ConverterFactory converterFactory;

		public Builder callAdapter(CallAdapter callAdapter) {
			this.adapter = callAdapter;
			return this;
		}

		public Builder converter(ConverterFactory converterFactory) {
			this.converterFactory = converterFactory;
			return this;
		}

		public MyRetrofit build() {
			if (adapter == null) {
				adapter = new SimpleCallAdapter();
			}

			if (converterFactory == null) {
				converterFactory = new GsonConverterFactory();
			}

			return new MyRetrofit(adapter, converterFactory);
		}
	}
}
